package com.akn.mvvmlibrary.network

import android.app.Activity
import com.akn.mvvmlibrary.utils.BaseEntity
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.Response
import com.lzy.okgo.request.base.Request
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog.Builder

abstract class StringDialogCallback() : StringCallback() {

    private var dialog: QMUITipDialog? = null

    constructor(activity: Activity) : this() {
        dialog = Builder(activity).setIconType(Builder.ICON_TYPE_LOADING).setTipWord("数据加载中...")
            .create(false)

    }

    abstract fun onRequestOk(body: String)

    open fun onRequestError() {

    }

    override fun onSuccess(response: Response<String>) {
        pareJson(response)
    }

    private fun pareJson(response: Response<String>) {
        try {
            val baseEntity: BaseEntity = GsonUtils.fromJson(response.body(), BaseEntity::class.java)
            if (baseEntity.status ==0) {
                onRequestOk(response.body())
            } else {
                onRequestError()
                ToastUtils.showShort(baseEntity.message)
            }
        } catch (e: Exception) {
            onRequestError()
            onError(response)
            LogUtils.e(e.message)
        }
    }


    override fun onError(response: Response<String>) {
        super.onError(response)
        onRequestError()
        ToastUtils.showShort(response.code().toString() + "-" + response.isSuccessful)
    }

    override fun onStart(request: Request<String, out Request<Any, Request<*, *>>>) {
        if (dialog != null && dialog?.isShowing != true) {
            dialog?.show()
        }
        //可以在这里处理请求头也可以构造拦截器来处理
    }


    override fun onFinish() {
        if (dialog != null && dialog?.isShowing == true) {
            dialog?.dismiss()
        }
    }
}